package com.flu.holidays.config;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.flu.holidays.constant.PropertiesConstant;
import com.flu.holidays.properties.HolidayDataSourceProperties;
import com.flu.holidays.service.HolidayService;
import com.flu.holidays.service.impl.db.HolidayServiceDbImpl;
import com.flu.holidays.service.impl.json.HolidayServiceJsonImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

//当holidays.datasource.type=db时生效
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(value = HolidayDataSourceProperties.class)
public class HolidayDatasourceConfiguration {


    @Bean
    @ConditionalOnProperty(prefix = PropertiesConstant.PREFIX,
            name = PropertiesConstant.DATASOURCE_TYPE,
            havingValue = "db")
    public HolidayService dbHolidayService() {
        return new HolidayServiceDbImpl();
    }

    @Bean
    @ConditionalOnProperty(prefix = PropertiesConstant.PREFIX,
            name = PropertiesConstant.DATASOURCE_TYPE, havingValue = "json")
    public HolidayService jsonHolidayService() {
        //holiday.json可以被覆盖，放到同样目录就行
        String holidayJsonStr = ResourceUtil.readStr("classpath:/json/holiday.json", StandardCharsets.UTF_8);
        JSONObject holidayJson = JSONUtil.parseObj(holidayJsonStr);
        return new HolidayServiceJsonImpl(holidayJson);
    }

}
